import React, { useState, useEffect, useRef } from "react";
import { Table, Button, Input, Select, Drawer, Form, Modal } from "antd";
import { get, getOne, gai, addOne, delOne, Twolook } from "../API/api";
function List() {
  const [data, setData] = useState([]);
  const { Option } = Select;
  // 分页
  const [pagination, setPagination] = useState({});
  // 抽屉框的动态标题
  const [AlertTitle, setAlertTitle] = useState("新增商品");
  // 控制抽屉弹窗时的状态
  const [visible, setVisible] = useState(false);
  // 用来存储新增和编辑时的id
  const currentId = useRef(""); // 用来保存当前正在编辑的数据的id
  // 获取表单内容的实例
  const [from] = Form.useForm();
  // 删除的时候弹出的提醒框
  const { confirm } = Modal;
  // 搜索输入框的值
  const [lookInput, setLookInput] = useState("");
  // 下拉菜单的值
  const [lookSele, setLookSele] = useState("请选择产地");
  useEffect(() => {
    get().then((res) => {
      setData(res.data);
      setPagination({
        total: res.data.length,
        pageSize: 5,
      });
    });
  }, []);
  const columns = [
    {
      title: "水果名称",
      dataIndex: "name",
      key: "name",
      render: (text) => <b>{text}</b>,
    },
    {
      title: "价格",
      dataIndex: "price",
      key: "price",
    },
    {
      title: "产地",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "操作",
      dataInex: "action",
      key: "action",
      render: (text, record) => (
        <span>
          <Button type="primary" ghost onClick={() => xiuOne(record.id)}>
            编辑
          </Button>
          <span>{"          "}</span>
          <Button type="primary" ghost onClick={() => del(record.id)}>
            删除
          </Button>
        </span>
      ),
    },
  ];

  // // 编辑一条数据
  const xiuOne = async (id) => {
    setVisible(true);
    setAlertTitle("修改商品");
    // 发送请求查询数据
    let res = await getOne(id);
    // 调用from的API重新给from实例更新内容
    from.setFieldsValue(res.data);
    // 保存当前点击的id
    currentId.current = id;
  };
  // 新增加一条数据
  const addShop = () => {
    setVisible(true);
    setAlertTitle("新增商品");
    currentId.current = "";
  };
  // // 表单完成触发的回调
  const Finish = async (values) => {
    if (currentId.current === "") {
      values.id = new Date().getTime();
      await addOne(values);
      setVisible(false);
      get().then((res) => {
        setData(res.data);
        setPagination({
          total: res.data.length,
          pageSize: 5,
        });
      });
    } else {
      await gai(currentId.current, values);
      setVisible(false);
      get().then((res) => {
        setData(res.data);

        setPagination({
          total: res.data.length,
          pageSize: 5,
        });
      });
    }
  };
  // // 点击删除触发的回调
  const del = (id) => {
    confirm({
      title: "删除",
      okText: "确定",
      cancelText: "取消",
      content: "此操作不可逆！确定删除吗？",
      async onOk() {
        await delOne(id);
        get().then((res) => {
          setData(res.data);
          setPagination({
            total: res.data.length,
            pageSize: 5,
          });
        });
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };
  // 点击搜索时触发的回调
  const getLook = async () => {
    let obj = {
      lookInput,
      lookSele,
    };
    let res = await Twolook(obj.lookInput, obj.lookSele);
    setData(res.data);
    setPagination({
      total: res.data.length,
      pageSize: 5,
    });
  };
  // 点击重置时触发的回调
  const clear = () => {
    get().then((res) => {
      setData(res.data);
      setPagination({
        total: res.data.length,
        pageSize: 5,
      });
      setLookInput("");
      setLookSele("请选择产地");
    });
  };
  return (
    <div>
      <Button type="primary" onClick={() => addShop()}>
        新增一项商品
      </Button>
      <br></br>
      <br></br>
      <Input
        size="default size"
        placeholder="请输入商品名称"
        style={{ width: 200, height: 30 }}
        onChange={(e) => setLookInput(e.target.value)}
        value={lookInput}
      />
      <span>{"          "}</span>
      <Select
        defaultValue={lookSele}
        style={{ width: 120 }}
        onChange={(v) => setLookSele(v)}
      >
        <Option value="西安">西安</Option>
        <Option value="三亚">三亚</Option>
        <Option value="湖南">湖南</Option>
        <Option value="新疆">新疆</Option>
      </Select>
      <br></br>
      <br></br>
      <Button type="primary" onClick={() => getLook()}>
        搜索
      </Button>
      <span>{"   "}</span>
      <Button type="primary" onClick={() => clear()}>
        重置
      </Button>
      <Table
        columns={columns}
        dataSource={data}
        key="id"
        dataIndex="id"
        pagination={pagination}
      />
      {/* 抽屉 */}
      <Drawer
        title={AlertTitle}
        placement="right"
        closable={true}
        onClose={() => setVisible(false)}
        visible={visible}
      >
        <Form onFinish={Finish} form={from} name="basic">
          <Form.Item label="商品名称" name="name">
            <Input />
          </Form.Item>
          <Form.Item label="商品价格" name="price">
            <Input />
          </Form.Item>
          <Form.Item label="商品产地" name="address">
            <Input />
          </Form.Item>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
          <Button
            onClick={(e) => {
              setVisible(false);
            }}
          >
            取消
          </Button>
        </Form>
      </Drawer>
    </div>
  );
}

export default List;
